<script lang="ts" setup>
import formPage from "./formPage.vue";
import { editItem } from "../service";
import { IResponseData } from "@/@types/utils.request";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, ref } from "vue";
import { formParams } from "../data";

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	id: {
		type: Number,
		default: 0,
	},

	editList: {
		type: Object,
		default: () => {},
	},
	courseTypeList: {
		type: Array<{ id: number; name: string }>,
		default: () => [],
	},
});

const emit = defineEmits<{
	(e: "update:modelValue", value: boolean): void;
	(e: "refresh", value: boolean): void;
}>();
const visible = computed({
	get() {
		return props.modelValue;
	},
	set(val) {
		emit("update:modelValue", !!val);
	},
});
const getInfo = () => {};

const edit = () => {
	return {
		courseTitle: "",
		courseType: "",
		courseCoverImage: "",
		courseContent: "",
		isChoices: 0,
		isShow: 0,
		sort: 0,
	};
};
watch(
	() => props.editList,
	(newVal) => {
		editData.value = newVal as formParams;
	},
);

const editData = ref<formParams>(edit());
const formRef = ref<any>();
const onConfirmm = async () => {
	if (!(await formRef.value.validate())) return;
	try {
		const response: IResponseData<any> = await editItem({
			...editData.value,
		});
		const { code, msg } = response;
		if (code === 0) {
			ElMessage({
				message: msg,
				type: "success",
			});
			formRef.value.resetFields();
			emit("refresh", true);
			emit("update:modelValue", false);
		} else {
			ElMessage({
				message: msg,
				type: "error",
			});
		}
	} catch (error: any) {
		console.log(error);
	}
};
const onCancel = () => {
	ElMessageBox.confirm("您所编辑的内容还未保存，此时退出会导致修改内容失效，确定要退出吗？", {
		confirmButtonText: "确认",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		formRef.value.resetFields();
		emit("update:modelValue", false);
	});
};
</script>
<template>
	<el-dialog
		v-model="visible"
		title="编辑"
		:close-on-press-escape="false"
		top="10vh"
		width="800px"
		@open="getInfo"
		:before-close="onCancel"
	>
		<formPage v-model="editData" :courseTypeList="courseTypeList" ref="formRef" />
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel">取消</el-button>
				<el-button type="primary" @click="onConfirmm"> 确认 </el-button>
			</span>
		</template>
	</el-dialog>
</template>
